package com.example.computer_exam_training_sys.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/pdf")
@CrossOrigin
public class PdfController {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * PDF文件解析接口
     */
    @PostMapping("/extract")
    public ResponseEntity<Map<String, Object>> extractQuestionsFromPdf(
            @RequestParam("file") MultipartFile file,
            @RequestParam("courseType") String courseType,
            @RequestParam("knowledgePoint") String knowledgePoint,
            @RequestParam("difficulty") String difficulty) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
                response.put("success", false);
                response.put("message", "只支持PDF格式文件");
                return ResponseEntity.badRequest().body(response);
            }

            // 提取PDF文本
            String extractedText = extractTextFromPdf(file);

            // 解析题目
            List<Map<String, Object>> questions = parseQuestionsFromText(extractedText, difficulty);

            response.put("success", true);
            response.put("extractedText", extractedText);
            response.put("questions", questions);
            response.put("message", "PDF解析成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "PDF解析失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从PDF文件中提取文本
     */
    private String extractTextFromPdf(MultipartFile file) throws IOException {
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            return pdfStripper.getText(document);
        }
    }

    /**
     * 从文本中解析题目
     */
    private List<Map<String, Object>> parseQuestionsFromText(String text, String difficulty) {
        List<Map<String, Object>> questions = new ArrayList<>();

        // 按行分割文本
        String[] lines = text.split("\n");

        // 题目模式识别
        List<String> questionPatterns = Arrays.asList(
                // 选择题模式
                "\\d+[、.．].*?[AaBbCcDd][、.．].*?[AaBbCcDd][、.．].*?[AaBbCcDd][、.．].*?[AaBbCcDd][、.．]",
                // 判断题模式
                "\\d+[、.．].*?[（(][对错√×TtFf][）)]",
                // 填空题模式
                "\\d+[、.．].*?[_＿]{2,}",
                // 简答题模式
                "\\d+[、.．].*?[？?]"
        );

        int questionIndex = 1;
        StringBuilder currentQuestion = new StringBuilder();
        boolean inQuestion = false;
        String currentQuestionType = "";

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            // 检测题目开始
            if (isQuestionStart(line)) {
                // 保存上一道题
                if (inQuestion && currentQuestion.length() > 0) {
                    Map<String, Object> question = createQuestionFromText(
                            currentQuestion.toString(),
                            currentQuestionType,
                            difficulty,
                            questionIndex++
                    );
                    if (question != null) {
                        questions.add(question);
                    }
                }

                // 开始新题目
                currentQuestion = new StringBuilder(line);
                currentQuestionType = detectQuestionType(line);
                inQuestion = true;
            } else if (inQuestion) {
                // 继续当前题目
                currentQuestion.append("\n").append(line);

                // 检查是否是答案行
                if (isAnswerLine(line)) {
                    Map<String, Object> question = createQuestionFromText(
                            currentQuestion.toString(),
                            currentQuestionType,
                            difficulty,
                            questionIndex++
                    );
                    if (question != null) {
                        questions.add(question);
                    }
                    inQuestion = false;
                    currentQuestion = new StringBuilder();
                }
            }
        }

        // 处理最后一道题
        if (inQuestion && currentQuestion.length() > 0) {
            Map<String, Object> question = createQuestionFromText(
                    currentQuestion.toString(),
                    currentQuestionType,
                    difficulty,
                    questionIndex
            );
            if (question != null) {
                questions.add(question);
            }
        }

        return questions;
    }

    /**
     * 检测是否是题目开始
     */
    private boolean isQuestionStart(String line) {
        // 匹配形如 "1." "1、" "（1）" 等开头的行
        Pattern pattern = Pattern.compile("^\\s*[（(]?\\d+[）)、.．]");
        return pattern.matcher(line).find();
    }

    /**
     * 检测题目类型
     */
    private String detectQuestionType(String text) {
        // 选择题：包含A、B、C、D选项
        if (text.contains("A.") || text.contains("A、") ||
                text.contains("B.") || text.contains("B、")) {
            return "选择题";
        }

        // 判断题：包含对错、√×、T F等
        if (text.matches(".*[（(][对错√×TtFf][）)].*")) {
            return "判断题";
        }

        // 填空题：包含下划线或空白填写区域
        if (text.contains("___") || text.contains("＿＿") ||
                text.contains("_____")) {
            return "填空题";
        }

        // 简答题：包含问号
        if (text.contains("？") || text.contains("?")) {
            return "简答题";
        }

        return "选择题"; // 默认为选择题
    }

    /**
     * 检测是否是答案行
     */
    private boolean isAnswerLine(String line) {
        // 匹配答案格式：答案：A 或 正确答案：A 等
        Pattern answerPattern = Pattern.compile("^\\s*[答正确]*案\\s*[：:：]\\s*[A-Da-d对错√×TtFf]");
        return answerPattern.matcher(line).find();
    }

    /**
     * 从文本创建题目对象
     */
    private Map<String, Object> createQuestionFromText(String text, String questionType,
                                                       String difficulty, int index) {
        try {
            Map<String, Object> question = new HashMap<>();

            // 基本信息
            question.put("id", "temp_" + index);
            question.put("questionType", questionType);
            question.put("difficulty", difficulty);

            // 解析题目内容和答案
            String[] parts = text.split("\\n");
            StringBuilder contentBuilder = new StringBuilder();
            String answer = "";
            String analysis = "";

            for (String part : parts) {
                part = part.trim();
                if (part.startsWith("答案") || part.startsWith("正确答案")) {
                    answer = extractAnswer(part);
                } else if (part.startsWith("解析") || part.startsWith("分析")) {
                    analysis = part.replaceFirst("^[解析分析]+\\s*[：:：]?\\s*", "");
                } else if (!part.isEmpty()) {
                    contentBuilder.append(part).append("\n");
                }
            }

            String content = contentBuilder.toString().trim();

            // 清理题目编号
            content = content.replaceFirst("^\\s*[（(]?\\d+[）)、.．]\\s*", "");

            question.put("content", content);
            question.put("answer", answer.isEmpty() ? "A" : answer); // 默认答案为A
            question.put("analysis", analysis);

            return question;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 提取答案
     */
    private String extractAnswer(String answerLine) {
        Pattern pattern = Pattern.compile("[：:：]\\s*([A-Da-d对错√×TtFf]+)");
        Matcher matcher = pattern.matcher(answerLine);
        if (matcher.find()) {
            return matcher.group(1).toUpperCase();
        }
        return "A"; // 默认答案
    }
}